package cn.azr.domain.strategy.service.armory;



import cn.azr.domain.strategy.model.entity.StrategyAwardEntity;
import cn.azr.domain.strategy.model.entity.StrategyEntity;
import cn.azr.domain.strategy.model.entity.StrategyRuleEntity;
import cn.azr.domain.strategy.repository.IStrategyRepository;
import cn.azr.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import  cn.azr.types.enums.ResponseCode;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

/**
 * ClassName:StrategyArmory
 * Description:
 * 策略装配实现类
 *
 * @version 1.0
 * @Author azr
 * @Create 2024/9/28 10:21
 */
@Slf4j
@Service

public class StrategyArmoryDispatch implements IStrategyArmory, IStrategyDispatch {

    @Resource
    private IStrategyRepository iStrategyRepository;

    @Override
    public boolean assembleLotteryStrategy(Long strategyId) {
        //1.查询策略配置
        List<StrategyAwardEntity> strategyAwardEntityList = iStrategyRepository.queryStrategyIdList(strategyId);
        assembleLotteryStrategy(String.valueOf(strategyId),strategyAwardEntityList);

        //2.配置rule_weight策略
        StrategyEntity strateEntity=iStrategyRepository.queryEntityByStrategyId(strategyId);
        String ruleWeight = strateEntity.getRuleWeight();
        if (null==ruleWeight)return true;

        StrategyRuleEntity strategyRuleEntity = iStrategyRepository.queryStrategyRule(strategyId, ruleWeight);
        if (null == strategyRuleEntity) {
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(), ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }
        Map<String, List<Integer>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();
        Set<String> keys = ruleWeightValueMap.keySet();
        for (String key : keys) {
            List<Integer> ruleWeightValues = ruleWeightValueMap.get(key);
            ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntityList);
            strategyAwardEntitiesClone.removeIf(entity -> !ruleWeightValues.contains(entity.getAwardId()));
            assembleLotteryStrategy(String.valueOf(strategyId).concat("_").concat(key), strategyAwardEntitiesClone);
        }
        return  true;



    }

    private  boolean assembleLotteryStrategy(String key, List<StrategyAwardEntity> strategyAwardEntityList){

        //1.获取概率最小值
        BigDecimal minAwardRate = strategyAwardEntityList.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

        //2.获取概率总和
        BigDecimal totalAwardRate = strategyAwardEntityList.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        //3.获取概率散列范围
        BigDecimal awardRateRange = totalAwardRate.divide(minAwardRate, 0, RoundingMode.CEILING);

        ArrayList<Integer> strategyAwardRateTables = new ArrayList<>(awardRateRange.intValue());

        //4.向tables添加各奖品概率对应奖品个数（以最小值做单位1）
        for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntityList) {
            Integer awardId = strategyAwardEntity.getAwardId();
            BigDecimal awardRate = strategyAwardEntity.getAwardRate();

            for (int i = 0; i < awardRateRange.multiply(awardRate).setScale(0, RoundingMode.CEILING).intValue(); i++) {
                strategyAwardRateTables.add(awardId);
            }
        }

        //5.乱序
        Collections.shuffle(strategyAwardRateTables);
        Map<Integer, Integer> shufflestrategyAwardRateTables = new HashMap<>();

        for (int i = 0; i < strategyAwardRateTables.size(); i++) {
            shufflestrategyAwardRateTables.put(i, strategyAwardRateTables.get(i));

        }

        //6.存入redis
        iStrategyRepository.store(key, awardRateRange, shufflestrategyAwardRateTables);
        return true;


    }


    @Override
    public Integer getRandomAwardId(Long strategyId) {

        //1.获取策略对应奖品数量范围
        int rateRange = iStrategyRepository.getRangeRate(strategyId);

        //2.实施抽奖通过生成的随机值，获取概率值奖品查找表的结果
        return iStrategyRepository.getStrategyAwardAssemble(String.valueOf(strategyId), new SecureRandom().nextInt(rateRange));


    }

    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {
        String key = String.valueOf(strategyId).concat("_").concat(ruleWeightValue);
        // 分布式部署下，不一定为当前应用做的策略装配。也就是值不一定会保存到本应用，而是分布式应用，所以需要从 Redis 中获取。
        int rateRange = iStrategyRepository.getRateRange(key);
        // 通过生成的随机值，获取概率值奖品查找表的结果
        return iStrategyRepository.getStrategyAwardAssemble(key, new SecureRandom().nextInt(rateRange));
    }


}
